package com.woniuxy.user.controller;

import com.woniuxy.user.service.ApprovalService;
import com.woniuxy.user.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 审批控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/approval")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class ApprovalController {

    @Autowired
    private ApprovalService approvalService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取当前用户的待办任务
     */
    @GetMapping("/tasks")
    public ResponseEntity<Map<String, Object>> getPendingTasks(HttpServletRequest request) {
        try {
            String currentUser = getCurrentUser(request);
            List<Map<String, Object>> tasks = approvalService.getPendingTasks(currentUser);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", tasks);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取待办任务失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取待办任务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 获取当前用户的已办任务
     */
    @GetMapping("/completed-tasks")
    public ResponseEntity<Map<String, Object>> getCompletedTasks(HttpServletRequest request) {
        try {
            String currentUser = getCurrentUser(request);
            List<Map<String, Object>> tasks = approvalService.getCompletedTasks(currentUser);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", tasks);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取已办任务失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取已办任务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 审批通过
     */
    @PostMapping("/approve")
    public ResponseEntity<Map<String, Object>> approveTask(@RequestParam String taskId,
                                                          @RequestParam(required = false) String comment,
                                                          HttpServletRequest request) {
        try {
            String currentUser = getCurrentUser(request);
            approvalService.approveTask(taskId, comment, currentUser);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "审批通过成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("审批通过失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "审批通过失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 审批拒绝
     */
    @PostMapping("/reject")
    public ResponseEntity<Map<String, Object>> rejectTask(@RequestParam String taskId,
                                                         @RequestParam String reason,
                                                         HttpServletRequest request) {
        try {
            String currentUser = getCurrentUser(request);
            approvalService.rejectTask(taskId, reason, currentUser);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "审批拒绝成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("审批拒绝失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "审批拒绝失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 获取审批历史
     */
    @GetMapping("/history")
    public ResponseEntity<Map<String, Object>> getApprovalHistory(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) String customerName,
            @RequestParam(required = false) String approvalResult,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            HttpServletRequest request) {
        try {
            String currentUser = getCurrentUser(request);
            
            Map<String, Object> params = new HashMap<>();
            params.put("userName", currentUser);
            params.put("page", page);
            params.put("size", size);
            params.put("orderNo", orderNo);
            params.put("customerName", customerName);
            params.put("approvalResult", approvalResult);
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            
            Map<String, Object> history = approvalService.getApprovalHistory(params);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", history);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取审批历史失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取审批历史失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 获取审批统计
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getApprovalStatistics(HttpServletRequest request) {
        try {
            String currentUser = getCurrentUser(request);
            Map<String, Object> statistics = approvalService.getApprovalStatistics(currentUser);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", statistics);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取审批统计失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "获取审批统计失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 从请求中获取当前用户信息
     */
    private String getCurrentUser(HttpServletRequest request) {
        // 优先从X-User-Name头获取用户名（网关可能会设置此头）
        String userName = request.getHeader("X-User-Name");
        if (userName != null && !userName.trim().isEmpty()) {
            log.debug("从X-User-Name头获取用户名：{}", userName);
            return userName;
        }
        
        // 从Authorization头获取token并解析
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            try {
                // 使用JwtUtil解析token获取用户名
                userName = jwtUtil.getUsernameFromToken(token);
                if (userName != null && !userName.trim().isEmpty()) {
                    log.debug("从JWT token解析用户名：{}", userName);
                    return userName;
                }
            } catch (Exception e) {
                log.warn("解析JWT token失败", e);
            }
        }
        
        // 从User-Info头获取用户信息
        String userInfo = request.getHeader("User-Info");
        if (userInfo != null && !userInfo.trim().isEmpty()) {
            log.debug("从User-Info头获取用户信息：{}", userInfo);
            return userInfo;
        }
        
        log.warn("无法从请求中获取用户信息，返回默认用户admin");
        return "admin"; // 默认用户
    }
}
